package unv.esiag.ihm;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import unv.esiag.uchiha.core.admin.impl.AddressControler;
import unv.esiag.uchiha.core.admin.impl.AdministratorImpl;
import unv.esiag.uchiha.core.admin.impl.GAdminControler;



public class JTest extends JFrame{
	private static final long serialVersionUID = 1L;
	private AdministratorImpl admin;
	private static Logger log=Logger.getLogger(JTest.class);
	public JTest() {
		this.setTitle("Admin");
		this.setSize(500, 500);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setAlwaysOnTop(true);

		DOMConfigurator.configure("log4j.xml");
		log.info("Lancement de d'application d'administrateur...");
		
		admin = AdministratorImpl.getInstance();
		
		new Thread(new Runnable() {
			
			public void run() {
				try{
					while(true){
						admin.signal();
						fillForm();
						Thread.sleep(1000);
					}
				}catch(Exception e){
					log.error("Erreur : "+e.getMessage());
					e.printStackTrace();
				}
			}
		}).start();
		
		this.setVisible(true);
		
	}
	
	public void fillForm(){
		
		int cols = 2;
		
		GAdminControler gestion = admin.getGestion();
		int rows = gestion.size() / cols;
		if(gestion.size() % cols != 0){
			rows++;
		}
		JPanel panel1 = new JPanel(new GridLayout(rows, cols));
		for(int i = 0; i < gestion.size(); i++){
			AddressControler ac = gestion.get(i);
			JPanel panel2 = new JPanel(new BorderLayout());
			panel2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), ac.getAddress()));
			JTextArea area = new JTextArea();
			try{
				if(ac.isConnected()){
					area.setText(ac.getControler().getArbre());
				}else {
					area.setText("La connexion est Interompue");
				}
			}catch(Exception e){
				area.setText("La connexion est Interompue");
				ac.setConnected(false);
			}
			
			panel2.add(area);
			if(ac.isInstance()){
				String item = "Stop";
				if(!ac.isConnected()){
					item = "Restart";
				}
				JButton butt = new JButton(item);
				butt.addActionListener(ac);
				panel2.add(butt, BorderLayout.SOUTH);
			}
			panel1.add(panel2);
		}
		invalidate();
		if(getContentPane().getComponentCount() != 0){
			getContentPane().remove(0);
		}
		getContentPane().add(panel1);
		validate();
	}
	
	public static void main(String[] args) {
		new JTest();
	}
}
